package com.seal.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.seal.comm.utils.Page;
import com.seal.dao.BaseDaoImpl;
import com.seal.dao.IDeptDao;
import com.seal.dto.DeptDto;
import com.seal.model.Dept;

@Service("deptDaoImpl")
@Transactional(readOnly = true)
public class DeptDaoImpl extends BaseDaoImpl implements IDeptDao {

	public void addDept(Dept ca) throws Exception {
		this.save(ca);
	}

	public void updateDept(Dept ca) throws Exception {
		this.update(ca);
	}

	public void deleteDept(Dept ca) throws Exception {
		this.delete(ca);
	}

	public Dept getDeptById(Long id) throws Exception {
		return (Dept) this.select(Dept.class, id);
	}

	public List<Dept> getAllDept(DeptDto deptDto, Page page) throws Exception {
		StringBuffer hql = new StringBuffer("from Dept t where 1=1 ");
		
		if (deptDto.getCompanyId() !=null) {
			hql.append(" and t.companyId = :companyId");
		}

		if (deptDto.getSid() !=null) {
			hql.append(" and t.sid = :sid");
		}
		
		if (null != deptDto.getDeptName() && !"".equals(deptDto.getDeptName())) {
			hql.append(" and t.deptName like :deptName");
		}

		Query query = this.getSession().createQuery(hql.toString());
		query.setProperties(deptDto);
		if (null != page) {
			query.setFirstResult(page.getFirstResult());
			query.setMaxResults(page.getPageSize());
			String countSql = "select count(t) " + hql.toString();

			Query queryCount = this.getSession().createQuery(countSql);
			queryCount.setProperties(deptDto);
			page.setTotalNumber(Integer.parseInt(queryCount.uniqueResult()
					.toString()));
		}
		return query.list();
	}
}
